﻿using AutoMapper;
using B.S.BaseData.Domain.Entities.Meeting;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.ErrorCode.ErrorCodes;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.DataBase.EFCoreServiers.Dtos.Meetings;
using B.S.DataBase.EFCoreServiers.IServices.Meetings;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.S.DataBase.EFCoreServiers.Services.Meetings
{
    public class MeetingRoomServices : IMeetingRoomServices
    {
        private readonly IMeetingRoomRepository meetingRoom;
        private readonly IMapper mapper;

        public MeetingRoomServices(IMeetingRoomRepository meetingRoom, IMapper mapper)
        {
            this.meetingRoom = meetingRoom;
            this.mapper = mapper;
        }

        /// <summary>
        /// 添加会议室
        /// </summary>
        /// <param name="addMeetingRoomDto"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddMeetingRoomAsync(AddMeetingRoomDto addMeetingRoomDto)
        {
            try
            {
                // 检查会议室名称是否已存在
                var existingRoom = await meetingRoom.GetAll()
                    .FirstOrDefaultAsync(x => x.Name == addMeetingRoomDto.Name);
                if (existingRoom != null)
                {
                    return ApiResult.Fail("会议室名称已存在", StatusCodeEnum.Fail);
                }

                var room = mapper.Map<MeetingRoom>(addMeetingRoomDto);
                await meetingRoom.AddAsync(room);

                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("添加会议室失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }

        /// <summary>
        /// 获取会议室列表
        /// </summary>
        /// <param name="getMeetingRoom"></param>
        /// <returns></returns>
        public async Task<ApiResult<ApiPaging<GetMeetingRoomResponseDto>>> GetDepartmentListAsync(GetMeetingRoomDto getMeetingRoom)
        {
            try
            {
                // 获取会议室列表分页
                var list = await meetingRoom.GetPageListAsync(
                    getMeetingRoom.pageIndex,
                    getMeetingRoom.pageSize,
                    x => (x.Name.Contains(getMeetingRoom.Name) || string.IsNullOrEmpty(getMeetingRoom.Name))
                );

                // 转换类型
                var dto = mapper.Map<IList<GetMeetingRoomResponseDto>>(list.Data);

                var pageDto = new ApiPaging<GetMeetingRoomResponseDto>(list.TotalCount, list.TotalPage, dto);
                return ApiResult<ApiPaging<GetMeetingRoomResponseDto>>.Success(pageDto, StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult<ApiPaging<GetMeetingRoomResponseDto>>.Fail(
                    "获取会议室列表失败：" + ex.Message,
                    StatusCodeEnum.Exception
                );
            }
        }

        /// <summary>
        /// 更新会议室信息
        /// </summary>
        /// <param name="updateMeetingRoom"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateMeetingRoomAsync(UpdateMeetingRoomDto updateMeetingRoom)
        {
            try
            {
                // 检查是否存在同名会议室（排除当前会议室）
                var exist = await meetingRoom.GetAll()
                    .AnyAsync(x => x.Name == updateMeetingRoom.Name && x.Id != updateMeetingRoom.Id);

                if (exist)
                {
                    return ApiResult.Fail("会议室名称已存在", StatusCodeEnum.Fail);
                }

                // 获取要更新的会议室
                var room = await meetingRoom.GetAll()
                    .FirstOrDefaultAsync(x => x.Id == updateMeetingRoom.Id);
                if (room == null)
                {
                    return ApiResult.Fail("会议室不存在", StatusCodeEnum.ObjNotFound);
                }

                // 更新会议室信息
                mapper.Map(updateMeetingRoom, room);
                await meetingRoom.UpdateAsync(room);

                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("更新会议室失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }

        /// <summary>
        /// 删除会议室
        /// </summary>
        /// <param name="Id">会议室ID</param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteMeetingRoomAsync(int Id)
        {
            try
            {
                var room = await meetingRoom.GetAll()
                    .FirstOrDefaultAsync(x => x.Id == Id);
                if (room == null)
                {
                    return ApiResult.Fail("会议室不存在", StatusCodeEnum.ObjNotFound);
                }

                await meetingRoom.DeleteAsync(room);
                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("删除会议室失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }
        /// <summary>
        /// 批量删除会议室
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ApiResult> DeleteMeetingRoomRangeAsync(string Id)
        {
            try
            {
                int[] ids = Id.Split(',').Select(int.Parse).ToArray();
                if (ids.Length == 0)
                {
                    return ApiResult.Fail("没有要删除的会议室ID", StatusCodeEnum.Fail);
                }
                // 获取要删除的会议室列表
                var rooms = await meetingRoom.GetAll()
                    .Where(x => ids.Contains(x.Id))// 使用Where筛选出要删除的会议室 包含ids数组中的ID
                    .ToListAsync();

                if (rooms == null)
                {
                    return ApiResult.Fail("会议室不存在", StatusCodeEnum.ObjNotFound);
                }
                var existingRooms =mapper.Map<IList<MeetingRoom>>(rooms);
                await meetingRoom.DeleteRangeAsync(existingRooms);
                return ApiResult.Success(StatusCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                return ApiResult.Fail("批量删除会议室失败：" + ex.Message, StatusCodeEnum.Exception);
            }
        }


    }
}
